﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

//Class that is used for searches
public partial class Search : System.Web.UI.Page
{
    protected override void OnPreRender(EventArgs e)
    {
        //handles prerendering issues
        Response.AppendHeader("P3P", "CP=\"CAO PSA OUR\"");     //handles cookie issues with IE
        base.OnPreRender(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Retrieve the search terms stored in the session
        SearchTerms = Session["searchTerm"].ToString().Split(' ');

        // Search based off of search terms
        performSearch();

        // Set customized fields on profile page
        searchHeaderLabel.Text = Session["searchTerm"].ToString();

    }

    public string[] SearchTerms
    {
        get;
        set;
    }

    /// <summary>
    /// Search based on user tags
    /// </summary>
    private void performSearch()
    {
        using (SqlConnection dbconn = new SqlConnection(Lutefisk.CONNECTION_STRING))
        {
            dbconn.Open();

            // In case the user enters < 3 search terms this code will make sure the search
            // is performed correctly.
            string searchTerm1 = SearchTerms.Length >= 1 ? SearchTerms[0] : "FAILURE";
            string searchTerm2 = SearchTerms.Length >= 2 ? SearchTerms[1] : "FAILURE";
            string searchTerm3 = SearchTerms.Length >= 3 ? SearchTerms[2] : "FAILURE";


            string searchString = "SELECT * FROM musicians WHERE tag1 like '%" + searchTerm1 + "%' OR tag2 like '%" + searchTerm2 + "%' OR tag3 like '%" + searchTerm3 + "%';";
            
            using (SqlCommand sql = new SqlCommand(searchString, dbconn))
            {
                using (SqlDataReader reader = sql.ExecuteReader())
                {
                    //this takes care of binding for the repeater
                    MusicianRepeater.DataSource = reader;
                    MusicianRepeater.DataBind();
                    int i = MusicianRepeater.Items.Count;
                    searchMessage.Text = "   " + i + " Item(s) Found.";
                }
            }
        }
    }

    protected void searchResultClick(Object sender, CommandEventArgs e)
    {
        // Redirect for profiles on search page
        Session["uid"] = (string)e.CommandArgument;
        Lutefisk.DirectPage(Page.Page, "Profile");
    }

}